﻿module Sustainalytics.EsgRatings {

    export class AnalystViewController {

        private esgCtrl: EsgController;

        public industryOverviewChartIsLoading: boolean = true;

        public keyEsgIssueValues: KeyEsgIssueValueDto[];
        public keyEsgIssueValuesXyChartOptions: any;
        public esgOverallAssessment: EsgOverallAssessmentDto;
        public keyEsgIssueIndicators: KeyEsgIssueIndicatorDto[];
        public keyEsgIssueInfoDic: Common.Dictionary<KeyEsgIssueInfo>;
        public keyEsgIssueAssessments: KeyEsgIssueAssessmentDto[];
        public subPeerGroup: string;

        private userId: string;

        constructor(
            private $rootScope: ng.IScope,
            private $scope: ng.IScope,
            private $q: ng.IQService,
            private $timeout: ng.ITimeoutService,
            private KeyEsgIssueValueService: IKeyEsgIssueValueService,
            private EsgOverallAssessmentService: IEsgOverallAssessmentService,
            private KeyEsgIssueIndicatorService: IKeyEsgIssueIndicatorService,
            private KeyEsgIssueAssessmentService: IKeyEsgIssueAssessmentService,
            private staticObjects: Common.IStaticObjects) {

            var ctx = this;

            if (ctx.$rootScope['userInfo'] == null) {
                ctx.$rootScope['userInfo'] = angular.fromJson(localStorage.getItem('sust_userInfo'));
            }
            ctx.userId = ctx.$rootScope['userInfo'].userId;

            // get ESG Controller from scope
            ctx.esgCtrl = $scope['esg'];

            $scope['analystView'] = ctx;

            var initPromise = ctx.init();
        }

        // init logic
        private init(): ng.IPromise<any> {
            var ctx = this;

            var promiseKeyEsgIssueValues = ctx.populateKeyEsgIssueValues();
            var promiseEsgOverallAssessment = ctx.populateEsgOverallAssessment();
            var promiseKeyEsgIssueIndicators = ctx.populateKeyEsgIssueIndicators();
            var promiseKeyEsgIssueAssessments = ctx.populateKeyEsgIssueAssessments();

            var promise = ctx.$q.all([promiseKeyEsgIssueValues, promiseEsgOverallAssessment, promiseKeyEsgIssueIndicators, promiseKeyEsgIssueAssessments]);

            ctx.subPeerGroup = ctx.esgCtrl.company.subPeerGroup;

            return promise;
        }


        private populateKeyEsgIssueValues(): ng.IPromise<KeyEsgIssueValueDto[]> {
            var ctx = this;

            var promise = ctx.KeyEsgIssueValueService.get(ctx.esgCtrl.company.id);

            promise.then(function (res) {
                ctx.$timeout(function () {
                    ctx.$scope.$apply(function () {
                        ctx.keyEsgIssueValues = ctx.formatKeyEsgIssueValues(res);
                        ctx.keyEsgIssueValuesXyChartOptions = ctx.createKeyEsgIssueValuesXyChartOptions();
                    });
                });
            },() => {

                    ga('create', 'UA-4379897-6', {
                        'userId': ctx.userId, 'cookieDomain': 'none', 'name': 'globalAccess'
                    });

                    ga('globalAccess.send', 'exception', { 'exDescription': 'Esg Ratings: AnalystViewController -> Error loading Key Esg Issues' });
                });

            //var promise = ctx.createKeyEsgIssueValuesFakeData();

            return promise;
        }

        public navigateTo(indicator: KeyEsgIssueIndicatorDto) {            

            if (indicator.isControversyIndicator) {
                var controversyIndicator = new Controversies.ControversyIndicatorDto();
                controversyIndicator.name = indicator.name;
                controversyIndicator.number = indicator.id;
                controversyIndicator.themeName = indicator.indicatorTheme;

                this.esgCtrl.goToControversyIndicator(controversyIndicator);
            }
            else {

                var targetView: string;
                if (this.esgCtrl.hasFocusRatings) {
                    switch (indicator.indicatorTheme) {
                        case "Environment":
                            targetView = EsgFocusView.Environment;
                            break;
                        case "Social":
                            targetView = EsgFocusView.Social;
                            break;
                        case "Governance":
                            targetView = EsgFocusView.Governance;
                            break;
                        default:
                            targetView = EsgFocusView.AnalystView;
                    }
                } else {
                    switch (indicator.indicatorTheme) {
                        case "Environment":
                            targetView = EsgViewNames.Environment;
                            break;
                        case "Social":
                            targetView = EsgViewNames.Social;
                            break;
                        case "Governance":
                            targetView = EsgViewNames.Governance;
                            break;
                        default:
                            targetView = EsgViewNames.AnalystView;
                    }
                }

                this.esgCtrl.changeView(targetView, indicator);
            }
        }

        public formatKeyEsgIssueValues(values: KeyEsgIssueValueDto[]): KeyEsgIssueValueDto[] {
            var ctx = this;

            if (!values)
                return null;

            var values = values.sort((a, b) => {
                if (a.keyEsgIssue.name < a.keyEsgIssue.name)
                    return 1;
                else
                    if (a.keyEsgIssue.name == b.keyEsgIssue.name)
                        return 0;
                    else
                        return -1;
            });

            $.each(values, function (index, val) {
                val['letter'] = String.fromCharCode(65 + index);
            });

            return values;
        }

        // create XY-Chart options
        private createKeyEsgIssueValuesXyChartOptions(): any {
            var ctx = this;

            // create chart data
            var data = [];

            if (ctx.keyEsgIssueValues) {
                $.each(ctx.keyEsgIssueValues, function (index, val) {
                    if (val.keyEsgIssue.selected) {
                        data.push(
                            {
                                x2: val.businessImpact,
                                y2: val.sustainabilityImpact,
                                value: val['letter']
                            });
                    }
                    else {
                        data.push(
                            {
                                x: val.businessImpact,
                                y: val.sustainabilityImpact,
                                value: val['letter']
                            });
                    }
                });
            }

            // create chart options
            var options =
                {
                    "marginLeft": 0,
                    "sequencedAnimation": false,
                    "theme": "light",
                    "trendLines": [],
                    "graphs": [
                        {
                            "balloonText": "x:<b>[[x]]</b> y:<b>[[y]]</b><br>value:<b>[[value]]</b>",
                            "bullet": "round",
                            "bulletBorderThickness": 1,
                            "bulletColor": "#5a6165",
                            "bulletSize": 20,
                            "color": "#FFFFFF",
                            "id": "AmGraph-1",
                            "labelPosition": "inside",
                            "labelText": "[[value]]",
                            "lineAlpha": 0,
                            "lineColor": "#5a6165",
                            "showAllValueLabels": true,
                            "valueField": "value",
                            "xField": "x",
                            "yField": "y",
                        },
                        {
                            "balloonText": "x:<b>[[x]]</b> y:<b>[[y]]</b><br>value:<b>[[value]]</b>",
                            "bullet": "round",
                            "bulletColor": "#23b1a5",
                            "bulletSize": 20,
                            "color": "#FFFFFF",
                            "fontSize": 12,
                            "id": "AmGraph-2",
                            "labelPosition": "inside",
                            "labelText": "[[value]]",
                            "lineAlpha": 0,
                            "lineColor": "#23b1a5",
                            "title": "",
                            "valueField": "value2",
                            "xField": "x2",
                            "yField": "y2",
                        }
                    ],
                    "guides": [
                        {
                            "fillAlpha": 0,
                            "fillColor": "#ff8000",
                            "fontSize": 13,
                            "id": "Guide-1",
                            "label": "Low",
                            "lineAlpha": 1,
                            "toValue": 0,
                            "value": 3,
                            "valueAxis": "ValueAxis-2"
                        },
                        {
                            "color": "#000000",
                            "fillAlpha": 0,
                            "fontSize": 13,
                            "id": "Guide-2",
                            "label": "Medium",
                            "toAngle": 0,
                            "toDate": "",
                            "toValue": 3,
                            "value": 7,
                            "valueAxis": "ValueAxis-2"
                        },
                        {
                            "fontSize": 13,
                            "id": "Guide-3",
                            "label": "High",
                            "labelRotation": 0,
                            "lineAlpha": 1,
                            "toValue": 7,
                            "value": 10,
                            "valueAxis": "ValueAxis-2"
                        },
                        {
                            "id": "Guide-4",
                            "label": "Low",
                            "labelRotation": -9,
                            "lineAlpha": 1,
                            "toValue": 0,
                            "value": 3.33,
                            "valueAxis": "ValueAxis-1"
                        },
                        {
                            "id": "Guide-5",
                            "label": "Medium",
                            "lineAlpha": 1,
                            "toValue": 3.33,
                            "value": 6.66,
                            "valueAxis": "ValueAxis-1"
                        },
                        {
                            "id": "Guide-6",
                            "label": "High",
                            "lineAlpha": 0,
                            "toValue": 6.66,
                            "value": 10,
                            "valueAxis": "ValueAxis-1"
                        }
                    ],
                    "valueAxes": [
                        {
                            "id": "ValueAxis-1",
                            "minimum": 0,
                            "maximum": 10,
                            "axisAlpha": 0,
                            "gridAlpha": 0,
                            "labelsEnabled": false,
                            "title": "Sustainability Impact"
                        },
                        {
                            "id": "ValueAxis-2",
                            "maximum": 10,
                            "minimum": 0,
                            "position": "bottom",
                            "axisAlpha": 0,
                            "gridAlpha": 0,
                            "labelsEnabled": false,
                            "title": "Business Impact"
                        }
                    ],
                    "allLabels": [],
                    "balloon": {},
                    "titles": [],
                    "dataProvider": data
                };

            return options;
        }


        private populateEsgOverallAssessment(): ng.IPromise<EsgOverallAssessmentDto> {
            var ctx = this;

            var promise = ctx.EsgOverallAssessmentService.get(ctx.esgCtrl.company.id);

            promise.then(function (res) {
                ctx.$timeout(function () {
                    ctx.$scope.$apply(function () {
                        ctx.esgOverallAssessment = res;
                    });
                });
            },() => {

                    ga('create', 'UA-4379897-6', {
                        'userId': ctx.userId, 'cookieDomain': 'none', 'name': 'globalAccess'
                    });

                    ga('globalAccess.send', 'exception', { 'exDescription': 'Esg Ratings: AnalystViewController -> Error populating Esg Overall Assessment' });
                });

            return promise;
        }

        private populateKeyEsgIssueIndicators(): ng.IPromise<KeyEsgIssueIndicatorDto[]> {
            var ctx = this;
            var promise = ctx.KeyEsgIssueIndicatorService.get(ctx.esgCtrl.company.id);

            promise.then(function (res) {
                ctx.$timeout(function () {
                    ctx.$scope.$apply(function () {
                        ctx.keyEsgIssueIndicators = res;
                        ctx.keyEsgIssueInfoDic = ctx.createKeyEsgIssueInfoDictionary(ctx.keyEsgIssueIndicators);
                    });
                });
            },() => {

                    ga('create', 'UA-4379897-6', {
                        'userId': ctx.userId, 'cookieDomain': 'none', 'name': 'globalAccess'
                    });

                    ga('globalAccess.send', 'exception', { 'exDescription': 'Esg Ratings: AnalystViewController -> Error populating Key Esg Issue Indicators' });
                });

            return promise;
        }

        // create a dictionary of Key ESG Issue Info (Key ESG Issue + RP Indicators Dictionary + Event Indicators Dictionary)
        private createKeyEsgIssueInfoDictionary(indicators: KeyEsgIssueIndicatorDto[]): Common.Dictionary<KeyEsgIssueInfo> {
            var ctx = this;
            var keyEsgIssueDic = new Common.Dictionary<KeyEsgIssueInfo>();

            $.each(indicators, function (index, indicator) {

                var info = keyEsgIssueDic.getValue(indicator.keyEsgIssue.name);

                if (!info) {
                    info = new KeyEsgIssueInfo(indicator.keyEsgIssue);
                    keyEsgIssueDic.add(indicator.keyEsgIssue.name, info);
                }

                indicator['companyScoreName'] = ctx.indicator_getCompanyScoreName(indicator);
                indicator['peerGroupAvgName'] = ctx.indicator_getPeerGroupAvgName(indicator);
                indicator['bestPracticeName'] = ctx.indicator_getBestPracticeName(indicator);
                indicator['materialBestPracticeGap'] = ctx.indicator_getMaterialBestPracticeGap(indicator);
                indicator['materialBestPracticeGapColor'] = ctx.indicator_getMaterialBestPracticeGapColor(indicator);

                info.addIndicator(indicator);
            });

            return keyEsgIssueDic;
        }

        public indicator_getCompanyScoreName(indicator: KeyEsgIssueIndicatorDto): string {
            var ctx = this;

            if (indicator.isEventIndicator) {

                return indicator.eventIndicatorScore.answerCategory;

            }
            else {

                return indicator.rpIndicatorScore.companyScore;

            }
        }

        public indicator_getPeerGroupAvgName(indicator: KeyEsgIssueIndicatorDto): string {
            var ctx = this;

            if (indicator.isEventIndicator) {

                return indicator.eventIndicatorScore.peerGroupAverage;

            }
            else {

                return indicator.rpIndicatorScore.peerGroupAverage;

            }
        }

        public indicator_getBestPracticeName(indicator: KeyEsgIssueIndicatorDto): string {
            var ctx = this;

            if (indicator.isEventIndicator) {

                return indicator.eventIndicatorScore.bestPractice;

            }
            else {

                return indicator.rpIndicatorScore.bestPractice;

            }
        }

        public indicator_getMaterialBestPracticeGap(indicator: KeyEsgIssueIndicatorDto): KeyEsgIssueIndicatorMaterialBestPracticeGap {
            var ctx = this;

            if (indicator.isEventIndicator) {
                return indicator.eventIndicatorScore.materialBestPracticeGap;
            }
            else {
                return indicator.rpIndicatorScore.materialBestPracticeGap;
            }
        }

        public indicator_getMaterialBestPracticeGapColor(indicator: KeyEsgIssueIndicatorDto): string {
            var ctx = this;

            var gap = ctx.indicator_getMaterialBestPracticeGap(indicator);

            switch (gap) {
                case KeyEsgIssueIndicatorMaterialBestPracticeGap.NA:
                    return null;
                case KeyEsgIssueIndicatorMaterialBestPracticeGap.Gray:
                    return '#acb0b2';
                case KeyEsgIssueIndicatorMaterialBestPracticeGap.Green:
                    return '#40ae49';
                case KeyEsgIssueIndicatorMaterialBestPracticeGap.Yellow:
                    return '#e7d600';
                case KeyEsgIssueIndicatorMaterialBestPracticeGap.Red:
                    return '#aa2b31';
            }
        }


        private populateKeyEsgIssueAssessments(): ng.IPromise<KeyEsgIssueAssessmentDto[]> {
            var ctx = this;
            var promise = ctx.KeyEsgIssueAssessmentService.get(ctx.esgCtrl.company.id);

            promise.then(function (res) {
                ctx.$timeout(function () {
                    ctx.$scope.$apply(function () {
                        ctx.keyEsgIssueAssessments = res;
                    });
                });
            },() => {

                    ga('create', 'UA-4379897-6', {
                        'userId': ctx.userId, 'cookieDomain': 'none', 'name': 'globalAccess'
                    });

                    ga('globalAccess.send', 'exception', { 'exDescription': 'Esg Ratings: AnalystViewController -> Error populating Key Esg Issue Assessments' });
                });

            return promise;
        }
    }


    angular.module(esgRatingsModuleName).controller('AnalystViewController',
        ['$rootScope', '$scope', '$q', '$timeout', 'KeyEsgIssueValueService', 'EsgOverallAssessmentService', 'KeyEsgIssueIndicatorService', 'KeyEsgIssueAssessmentService', 'staticObjects', AnalystViewController]);
}